import java.util.Random;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: zch
 * @Date: 2019/1/8 17:02
 * @Description:
 */
public class Producer implements Runnable {

    private volatile boolean isRunning = true;
    private BlockingDeque<PCData>blockingDeque;
    private static AtomicInteger count = new AtomicInteger();
    private static final int SLEEPTIME = 1000;



    public Producer(BlockingDeque<PCData> blockingDeque) {
        this.blockingDeque = blockingDeque;
    }


    @Override
    public void run() {

        PCData data = null;
        Random r = new Random();
        System.out.println("start producer id=" + Thread.currentThread().getId());
        try {
            while (isRunning) {
                Thread.sleep(r.nextInt(SLEEPTIME));
                data = new PCData((count.incrementAndGet()));
                System.out.println(data+" is put into queue");
                if (!blockingDeque.offer(data, 2, TimeUnit.SECONDS)) {
                    System.out.println("failed to put data:"+data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }

    }
    public void stop() {
        isRunning = false;
    }
}
